package com.adinnet.api.common.config.interceptor;

import com.adinnet.api.common.model.AuthUtil;
import com.adinnet.api.user.mapper.UserMapper;
import com.adinnet.api.user.model.User;
import com.adinnet.api.user.service.UserService;
import com.adinnet.common.utils.ResponseUtil;
import com.adinnet.core.BizResult;
import com.adinnet.core.redis.RedisConstant;
import com.adinnet.core.redis.RedisService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.support.WebApplicationContextUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;

//@Configuration
public class OauthInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    private RedisService redisService;

    @Autowired
    private UserMapper userMapper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String accessToken = request.getHeader("accessToken");
        if (StringUtils.isBlank(accessToken)) {
            ResponseUtil.responeJsonStr(200, response, new BizResult<>(401, "token为空，请先登录！"));
            return false;
        }
        if (redisService == null) {//解决service为null无法注入问题
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            redisService = (RedisService) factory.getBean("redisService");
        }
        if (userMapper == null) {//解决service为null无法注入问题
            BeanFactory factory = WebApplicationContextUtils.getRequiredWebApplicationContext(request.getServletContext());
            userMapper = (UserMapper) factory.getBean("userMapper");
        }
        String redisKey = RedisConstant.PATIENT_LOGIN_KEY + accessToken;
        if (!redisService.exists(redisKey)) {
            ResponseUtil.responeJsonStr(200, response, new BizResult<>(401, "登陆过期或失效，请重新登录"));
            return false;
        }
        User user = (User) redisService.get(redisKey);
        if ((null == user)) {
            ResponseUtil.responeJsonStr(200, response, new BizResult<>(401, "登陆过期或失效，请重新登录"));
            return false;
        }
        //【管理后台】学员被禁用，前端刷新页面就要告知状态禁用,由于redis的数据还没刷新,查询一次新的数据
        User u1 = userMapper.selectById(user.getId());
        if(u1.getStatus()!=null&&u1.getStatus()==1){
            ResponseUtil.responeJsonStr(200, response, new BizResult<>(401, "账号已被禁用"));
            return false;
        }
        if(u1.getDeleted()!=null&&u1.getDeleted()==1){
            ResponseUtil.responeJsonStr(200, response, new BizResult<>(401, "账号已被删除"));
            return false;
        }
        //体验学员体验周期一个月到期后不能使用app
        if(null!=u1.getStudentType()&&u1.getStudentType()==2&&null!=u1.getLastExperienceTime()){
            Date date = new Date();
            if(date.after(u1.getLastExperienceTime())){
                ResponseUtil.responeJsonStr(200, response, new BizResult<>(401, "体验周期已过，无法使用应用"));
                return false;
            }
        }
        redisService.expire(redisKey, RedisConstant.TOKEN_SURVIVE_TIME);
        AuthUtil.setLoginUser(user);
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView
            modelAndView) throws Exception {
        super.postHandle(request, response, handler, modelAndView);
        AuthUtil.clear();
    }
}
